<?php
declare (strict_types = 1);

namespace app\getway\controller;
use app\getway\model\WorkerTime as WorkerTimeModel;

class Index
{
    public function index($lat,$lng,$distance)
    {
        $lat = (float)$lat;
        $lng = (float)$lng;
        $squares = $this->returnSquarePoint($lng, $lat,$distance);

        $where = [];
        $where[] = ['start_work_lat','<>',0];
        $where[] = ['start_work_lat','>',$squares['right-bottom']['lat']];
        $where[] = ['start_work_lat','<',$squares['left-top']['lat']];
        $where[] = ['start_work_lng','<',$squares['left-top']['lng']];
        $where[] = ['start_work_lng','>',$squares['right-bottom']['lng']];

        $WorkerTimeModel = new WorkerTimeModel();
        $list = $WorkerTimeModel->field('*')->where($where)->select();

        $data['location'] = $list;
        $data['sql'] = $WorkerTimeModel->getLastSql();
        return json($data);
    }

    /**
     * 获取周围坐标
     * Enter description here ...
     * @param unknown_type $lng  固定坐标经度
     * @param unknown_type $lat  固定坐标纬度
     * @param unknown_type $distance  搜索周边距离，单位KM
     * @return multitype:multitype:number
     */
    private function returnSquarePoint($lng, $lat,$distance = 1){
        $earthRadius = 6378.138; //地球半径，单位KM
        $dlng =  2 * asin(sin($distance / (2 * $earthRadius)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance/$earthRadius;
        $dlat = rad2deg($dlat);
        return array(
            'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
            'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
            'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
            'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
        );
    }

    //计算两个坐标的直线距离
    private function getDistance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6378.138; //近似地球半径千米
        // 转换为弧度
        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;
        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;
        // 使用半正矢公式  用尺规来计算
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }

}
